<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '采购订单' : '采购订单'"
    :toolbar-attrs="{
      buttons: [
        'back',
        {
          save: true,
          submit: hasBtn('submit'),
          withdraw: flowContext.canWithdraw,
          reject: flowContext.canReject,
          finish: hasBtn('finish')
        }
      ]
    }"
    :toolbar-listeners="{
      save: () => saveAndStart({ title: `${userName}的采购订单${entity.caseid}`, variables: { days: entity.days } }),
      submit: submitAudit,
      finish: () => submitAudit(),
      withdraw: () => withdrawAudit(),
      reject: () => reject()
    }">
    <FormHolder ref="form" label-width="100px" :model="entity" :disabled="entity.status === '2'">
      <FormItemGroup block-title="基本信息">
        <FormTreeSelect
          v-model="entity.deptId"
          :span="12"
          label="采购单位"
          :options="dictData.deptTreeList"
          prop="deptId"
          disabled />
        <FormInput v-model="entity.caseid" prop="caseid" label="采购单号" disabled />
        <FormInput v-model="entity.parentCaseid" prop="parentCaseid" label="申请单号" disabled />
        <FormInput v-model="entity.createBy" prop="createBy" label="采购人" disabled />
        <FormSelect
          v-model="entity.status"
          :options="dictData.statusList"
          prop="status"
          legacy
          value-prop="value"
          label-prop="label"
          label="状态"
          disabled />
        <FormDatePicker v-model="entity.orderDatetime" date-time label="订购时间" prop="orderDatetime" required />
        <FormDatePicker v-model="entity.arrivalDatetime" date-time label="到货时间" prop="arrivalDatetime" required />
        <FormSelect
          v-model="entity.contractId"
          :options="dictData.contractTreeList"
          prop="contractId"
          legacy
          value-prop="id"
          filterable
          label-prop="name"
          label="合同或发票"
          required />
        <FormSelect
          v-model="entity.supplierId"
          :options="dictData.supplierTreeList"
          prop="supplierId"
          legacy
          value-prop="id"
          filterable
          label-prop="name"
          label="供应商" />
        <FormSelect
          v-model="entity.method"
          label="采购方式"
          :options="dictData.purchaseWayList"
          prop="method"
          required />
        <FormInputNumber v-model="entity.amount" label="购置金额" prop="amount" disabled />
        <FormSelect
          v-model="entity.currencyType"
          dict-type="currency_type"
          classic
          label="货币类型"
          prop="currencyType" />
        <FormInput v-model="entity.receivinfo" :span="24" label="收货信息" prop="receivinfo" max-length="255" />
        <FormTextarea v-model="entity.explains" rows="5" label="订单说明" prop="explains" max-length="3000" />
        <FormInput v-show="false" v-model="entity.type" prop="type" label="类型" disabled />
        <ElCol :span="24">
          <FlexRow vertical-center style="padding: 10px">
            <FlexItem><span style="color: #f56c6c">*</span>申请明细-物品列表</FlexItem>
            <ElButton size="mini" type="primary" class="el-icon-circle-plus" @click="tableVisible = true">
              从申请单选择</ElButton
            >
            <ElButton size="mini" type="primary" class="el-icon-delete" @click="deleteSelectCard"> 删除所选</ElButton>
          </FlexRow>
          <FormTable
            ref="formTable"
            v-model="entity.purchaseOrderList"
            prop="purchaseOrderList"
            required
            selection-width="60"
            placeholder="请选择物品"
            editable
            :show-summary="true"
            hide-label
            :handle-column="false"
            :columns="[
              { label: '名称', prop: 'name' },
              { label: '规格型号', prop: 'model' },
              { label: '计量单位', prop: 'unit' },
              { label: '单价', prop: 'price' },
              { label: '申请数量', prop: 'quantity' },
              { label: '已购数量', prop: 'orderQuantity', required: true, type: 'number' },
              { label: '采购数量', prop: 'purchasedQuantity', required: true, type: 'number' },
              { label: '金额', prop: 'amount' },
              { label: '申请编号', prop: 'parentCaseid' },
              { label: '申请单位', prop: 'deptFullname' }
            ]" />
        </ElCol>
      </FormItemGroup>
      <FormItemGroup :gutter="0" block-title="附件信息">
        <UploadPage
          ref="UploadPage"
          style="padding: 0"
          :unique-code="entity.unid"
          model="purchaseOrder"
          classify="purchaseOrder" />
      </FormItemGroup>
    </FormHolder>
    <!-- 流程发送选择框 -->
    <FlowableHandleUserTable :visible.sync="visibleUser" :selection="true" :multiple="true" />
    <SelectApplyListTable :visible.sync="tableVisible" :join-purchaseorder="true" @confirm="onApplyList" />
  </FormView>
</template>

<script>
  import { fetchList, addObj, putObj, create, edit } from '@/api/asset/fyassetpurchaseorder'

  import flowForm from '@/vue/mixin/flow-form'
  import { delPurchaseOrderListObj } from '@/api/asset/fyassetpurchaseorderlist.js'
  import FlowableHandleUserTable from '@/module/process/components/FlowableHandleUserTable.vue'

  export default {
    name: 'PurchaseorderForm',
    docType: 'PurchaseorderFlowCode',
    relativeViewId: 'PurchaseorderView',
    components: { FlowableHandleUserTable },
    mixins: [flowForm],
    data() {
      return {
        rows: [],
        selectedRows: [],
        tableVisible: false,
        visibleUser: false,
        entity: {
          id: '',
          deptId: '254',
          deptFullname: '广州海洋地质调查局',
          createBy: 'liyue',
          createId: '1187',
          createTime: '2023-04-24 10:54:27',
          updateBy: null,
          updateTime: null,
          unid: '7a1ff59f-1bfb-4fa5-a634-9c21f28bcac9',
          type: 'ALL',
          caseid: null,
          parentId: null,
          parentCaseid: null,
          batchnumber: null,
          contractId: null,
          contractNumber: null,
          contractName: null,
          status: '0',
          supplierId: null,
          supplierName: null,
          receivinfo: null,
          orderDatetime: null,
          arrivalDatetime: null,
          method: null,
          amount: null,
          currencyType: '人民币',
          detailed: '',
          explains: '',
          purchaseOrderList: [],
          dictOption: {
            statusList: [],
            purchaseWayList: [],
            currencyTypeList: [],
            contractTreeList: [],
            supplierTreeList: [],
            deptTreeList: []
          }
        }
      }
    },
    computed: {},
    created() {
      this.init()
    },
    methods: {
      create,
      load: edit,
      save: addObj,
      update: putObj,
      onApplyList(rows) {
        if (!this.entity.purchaseapplyList?.length) {
          rows.forEach(value => {
            this.$set(value, 'id', null)
            this.$set(value, 'orderQuantity', value.quantity || undefined)
          })
          this.entity.purchaseOrderList = rows
        } else {
          rows.forEach(row => {
            this.$set(row, 'id', null)
            this.$set(row, 'orderQuantity', row.quantity || undefined)
            if (!this.entity.purchaseOrderList.find(value => value.sauId === row.sauId)) {
              this.entity.purchaseOrderList.push(row)
            }
          })
        }
        const row = rows[0]
        this.entity.type = row.type
        this.entity.batchnumber = row.batchnumber
        this.entity.supplierId = row.supplierId
        this.entity.supplierName = row.supplierName
        this.entity.receivinfo = row.receivinfo
        this.entity.method = row.method
        this.entity.currencyType = row.currencyType
        this.entity.parentId = row.parentId
        this.entity.parentCaseid = row.parentCaseid
      },
      init() {},
      getPage(page) {
        return fetchList({ current: page.page, size: page.limit })
      },
      onConfirm(rows) {
        this.rows = rows
      },
      onChange(rows) {
        this.selectedRows = rows
      },
      del() {
        this.rows = this.rows.filter(value => !this.selectedRows.includes(value))
      },
      // 单击事件
      ellClick(row, column) {
        row.seen = true
      },
      cellDblclick(row, column) {
        row.seen = true
      },
      confirm() {},
      deleteSelectCard() {
        this.selectedRows = this.$refs.formTable.selectedRows
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择所需要删除的物品列表')
          return
        }
        const deleteIds = this.selectedRows.filter(item => item.id > 0).map(item => item.id)
        this.$confirm(`是否确认删除"${this.selectedRows.length} "条明细数据？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (deleteIds.length > 0) {
              delPurchaseOrderListObj(deleteIds)
            }
            this.entity.purchaseOrderList = this.entity.purchaseOrderList.filter(
              value => !this.selectedRows.includes(value)
            )
          })
          .then(data => {
            this.$message.success('删除成功')
          })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .ui-dialog {
    .el-dialog {
      @include flex-column;

      &.is-fullscreen {
        top: 0 !important;
        left: 0 !important;
      }

      .el-dialog__header {
        min-height: unset;
        padding: 16px 24px;
        border-bottom: 1px solid #f0f0f0;
      }

      .el-dialog__body {
        flex: 1;
        margin-bottom: 0;
        padding: 0;
        overflow: hidden;
      }

      .el-dialog__footer {
        padding: 10px 16px;
      }
    }
  }
</style>
